#### This script loads the ANES cumulative file and
#### recodes the relevant variables for analysis

rm(list=ls(all=TRUE))
set.seed(221269)


library(foreign)
library(haven)
library(car)


#### Load ANES cumulative
## First, set your working directory. 
## Make sure the ANES cumulative data set is there! 
## setwd()

anes <- foreign::read.spss(file="anes_timeseries_cdf_spss_20220916.sav",
                  use.value.labels=FALSE, to.data.frame=TRUE)


## Selecting the relevant years
anes <- subset(anes, (VCF0004==1992 | VCF0004==2000 | 
                        VCF0004==2004 | VCF0004==2008 | 
                        VCF0004==2012 | VCF0004==2016))

## Selecting cases with post-election data
## (items on child-rearing are administered in the post-election survey)
anes <- subset(anes, (VCF0013==1))

## Exclude survey online interviews
anes <- subset(anes, (VCF0017!=4))

## Retain blacks and whites, exclude others
anes <- subset(anes, (VCF0106!=3))


################
#### Recode ####
################

#### Race ####
# VCF0106: First question one race. 
anes$race <- car::recode(anes$VCF0106, 
                         "1 ='White'; 2='Black'", 
                         as.factor=TRUE, 
                         levels=c("White", "Black"))


#### Child-rearing values ####
## All variables are recoded
## Authoritarian = 3
## Both = 2
## Non-authoritarian = 1

# Curiosity v Good manners
anes$manners <- car::recode(anes$VCF9246, 
                            "1=1; 2=2; 3=3; else=NA")
# Obedience v Self-reliance
anes$obedience <- car::recode(anes$VCF9247, 
                              "1=3; 2=2; 3=1; else=NA")
# Being considerate v Well behaved
anes$behaved <- car::recode(anes$VCF9248, 
                            "1=1; 2=2; 3=3; else=NA")
# Independence v Respect for elders
anes$respect <- car::recode(anes$VCF9249, 
                            "1=1; 2=2; 3=3; else=NA")


#### Survey design ####
# Year 
anes$year <- anes$VCF0004
# Weight
anes$weight <- anes$VCF0009x


#### Save data
for (y in unique(anes$year)) {
  tmp_name <- paste0("anes", y)
  assign(x = tmp_name, value = subset(anes, year == y))
  filename <- paste0(tmp_name, ".RData")
  save(list = tmp_name, file = filename)
}
